<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>项目详情</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body class="bg-gray-50">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-sm border-b">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <a href="/dashboard" class="text-gray-500 hover:text-gray-700 mr-4">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                        </svg>
                    </a>
                    <h1 id="projectName" class="text-xl font-semibold text-gray-900">项目详情</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <button id="newItemBtn" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium">
                        新建Item
                    </button>
                    <button id="archiveBtn" class="bg-orange-600 hover:bg-orange-700 text-white px-4 py-2 rounded-lg text-sm font-medium">
                        归档项目
                    </button>
                    <button id="logoutBtn" class="text-gray-500 hover:text-gray-700 text-sm">
                        退出登录
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <main class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        <!-- 项目信息 -->
        <div class="bg-white rounded-lg shadow-sm border p-6 mb-6">
            <div class="flex justify-between items-start">
                <div>
                    <h2 id="projectTitle" class="text-2xl font-bold text-gray-900 mb-2"></h2>
                    <p id="projectDescription" class="text-gray-600 mb-4"></p>
                    <div class="text-sm text-gray-500">
                        创建于 <span id="projectCreatedAt"></span>
                    </div>
                </div>
                <div class="text-right">
                    <div class="text-sm text-gray-500 mb-2">项目统计</div>
                    <div class="flex space-x-4">
                        <div class="text-center">
                            <div id="taskCount" class="text-2xl font-bold text-green-600">0</div>
                            <div class="text-xs text-gray-500">任务</div>
                        </div>
                        <div class="text-center">
                            <div id="issueCount" class="text-2xl font-bold text-red-600">0</div>
                            <div class="text-xs text-gray-500">问题</div>
                        </div>
                        <div class="text-center">
                            <div id="requirementCount" class="text-2xl font-bold text-blue-600">0</div>
                            <div class="text-xs text-gray-500">需求</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tab导航 -->
        <div class="bg-white rounded-lg shadow-sm border mb-6">
            <div class="border-b border-gray-200">
                <nav class="-mb-px flex space-x-8 px-6">
                    <button class="tab-btn active py-4 px-1 border-b-2 border-blue-500 text-blue-600 font-medium text-sm" data-type="task">
                        任务
                    </button>
                    <button class="tab-btn py-4 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium text-sm" data-type="issue">
                        问题
                    </button>
                    <button class="tab-btn py-4 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium text-sm" data-type="requirement">
                        需求
                    </button>
                </nav>
            </div>

            <!-- Tab内容 -->
            <div class="p-6">
                <!-- 筛选和搜索 -->
                <div class="flex justify-between items-center mb-6">
                    <div class="flex space-x-4">
                        <select id="statusFilter" class="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">所有状态</option>
                            <option value="pending">待处理</option>
                            <option value="in_progress">进行中</option>
                            <option value="completed">已完成</option>
                            <option value="closed">已关闭</option>
                        </select>
                        <select id="priorityFilter" class="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">所有优先级</option>
                            <option value="low">低</option>
                            <option value="medium">中</option>
                            <option value="high">高</option>
                            <option value="urgent">紧急</option>
                        </select>
                    </div>
                    <div class="flex space-x-2">
                        <input type="text" id="searchInput" placeholder="搜索..." 
                               class="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <button id="searchBtn" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-md text-sm">
                            搜索
                        </button>
                    </div>
                </div>

                <!-- Items列表 - Table形式 -->
                <div class="bg-white rounded-lg border overflow-hidden">
                    <!-- Table头部 -->
                    <div class="bg-gray-50 border-b border-gray-200">
                        <div class="grid grid-cols-12 gap-4 px-4 py-3 text-sm font-medium text-gray-700">
                            <div class="col-span-4">标题</div>
                            <div class="col-span-2">状态</div>
                            <div class="col-span-1">优先级</div>
                            <div class="col-span-2">负责人</div>
                            <div class="col-span-2">创建时间</div>
                            <div class="col-span-1">操作</div>
                        </div>
                    </div>
                    <!-- Items列表 -->
                    <div id="itemsList" class="divide-y divide-gray-200">
                        <!-- Items将通过JavaScript动态加载 -->
                    </div>
                </div>

                <!-- 分页 -->
                <div id="pagination" class="flex justify-center mt-6">
                    <!-- 分页控件将通过JavaScript动态生成 -->
                </div>
            </div>
        </div>
    </main>


    <script>
        let currentProject = null;
        let currentType = 'task';
        let currentPage = 1;
        let pageSize = 50; // 增加每页显示数量

        $(document).ready(function() {
            const projectId = window.location.pathname.split('/').pop();
            loadProject(projectId);
            loadItems(projectId, currentType);
            
            // Tab切换事件
            $('.tab-btn').click(function() {
                $('.tab-btn').removeClass('active border-blue-500 text-blue-600').addClass('border-transparent text-gray-500');
                $(this).addClass('active border-blue-500 text-blue-600').removeClass('border-transparent text-gray-500');
                
                currentType = $(this).data('type');
                currentPage = 1;
                loadItems(projectId, currentType);
            });
            
            // 新建Item按钮事件 - 跳转到新建页面
            $('#newItemBtn').click(function() {
                const currentType = $('.tab-btn.active').data('type');
                window.location.href = `/items/new?project_id=${projectId}&type=${currentType}`;
            });
            
            // 归档项目按钮事件
            $('#archiveBtn').click(function() {
                if (confirm('确定要归档这个项目吗？归档后项目将不会在Dashboard中显示。')) {
                    $.ajax({
                        url: `/api/projects/${projectId}/archive`,
                        method: 'POST',
                        success: function(response) {
                            showNotification('项目已成功归档！', 'success');
                            setTimeout(function() {
                                window.location.href = '/dashboard';
                            }, 1500);
                        },
                        error: function(xhr) {
                            const error = xhr.responseJSON?.error || '归档项目失败';
                            showNotification(error, 'error');
                        }
                    });
                }
            });
            
            // 筛选和搜索事件
            $('#statusFilter, #priorityFilter').change(function() {
                currentPage = 1;
                loadItems(projectId, currentType);
            });
            
            $('#searchBtn').click(function() {
                currentPage = 1;
                loadItems(projectId, currentType);
            });
            
            $('#searchInput').keypress(function(e) {
                if (e.which === 13) {
                    currentPage = 1;
                    loadItems(projectId, currentType);
                }
            });
            
            // 退出登录
            $('#logoutBtn').click(function() {
                $.ajax({
                    url: '/api/logout',
                    method: 'POST',
                    success: function() {
                        window.location.href = '/login';
                    }
                });
            });
        });
        
        function loadProject(projectId) {
            $.ajax({
                url: `/api/projects/${projectId}`,
                method: 'GET',
                success: function(response) {
                    currentProject = response.project;
                    $('#projectName').text(currentProject.name);
                    $('#projectTitle').text(currentProject.name);
                    $('#projectDescription').text(currentProject.description || '暂无描述');
                    $('#projectCreatedAt').text(new Date(currentProject.created_at).toLocaleDateString());
                },
                error: function(xhr) {
                    console.error('Failed to load project:', xhr);
                    showNotification('加载项目失败', 'error');
                }
            });
            
            // 加载项目统计信息
            $.ajax({
                url: '/api/projects',
                method: 'GET',
                success: function(response) {
                    const project = response.projects.find(p => p.id == projectId);
                    if (project) {
                        $('#taskCount').text(project.task_count);
                        $('#issueCount').text(project.issue_count);
                        $('#requirementCount').text(project.requirement_count);
                    }
                }
            });
        }
        
        function loadItems(projectId, type) {
            const params = {
                project_id: projectId,
                type: type,
                page: currentPage,
                limit: pageSize
            };
            
            const status = $('#statusFilter').val();
            const priority = $('#priorityFilter').val();
            const search = $('#searchInput').val();
            
            if (status) params.status = status;
            if (priority) params.priority = priority;
            if (search) params.search = search;
            
            $.ajax({
                url: '/api/items',
                method: 'GET',
                data: params,
                success: function(response) {
                    displayItems(response.items);
                },
                error: function(xhr) {
                    console.error('Failed to load items:', xhr);
                    showNotification('加载Items失败', 'error');
                }
            });
        }
        
        function displayItems(items) {
            const container = $('#itemsList');
            container.empty();
            
            if (items.length === 0) {
                container.html(`
                    <div class="text-center py-8 text-gray-500 col-span-12">
                        暂无${getTypeName(currentType)}
                    </div>
                `);
                return;
            }
            
            items.forEach(function(item) {
                const itemElement = createItemElement(item);
                container.append(itemElement);
            });
        }
        
        function createItemElement(item) {
            const statusColors = {
                'pending': 'bg-yellow-100 text-yellow-800',
                'in_progress': 'bg-blue-100 text-blue-800',
                'completed': 'bg-green-100 text-green-800',
                'closed': 'bg-gray-100 text-gray-800'
            };
            
            const priorityColors = {
                'low': 'bg-gray-100 text-gray-800',
                'medium': 'bg-blue-100 text-blue-800',
                'high': 'bg-orange-100 text-orange-800',
                'urgent': 'bg-red-100 text-red-800'
            };
            
            const statusNames = {
                'pending': '待处理',
                'in_progress': '进行中',
                'completed': '已完成',
                'closed': '已关闭'
            };
            
            const priorityNames = {
                'low': '低',
                'medium': '中',
                'high': '高',
                'urgent': '紧急'
            };
            
            return $(`
                <div class="grid grid-cols-12 gap-4 px-4 py-3 hover:bg-gray-50 cursor-pointer item-card" data-item-id="${item.id}">
                    <!-- 标题列 -->
                    <div class="col-span-4">
                        <div class="font-medium text-gray-900 truncate" title="${item.title}">${item.title}</div>
                        <div class="text-sm text-gray-500 truncate mt-1" title="${item.description || '暂无描述'}">${item.description || '暂无描述'}</div>
                    </div>
                    <!-- 状态列 -->
                    <div class="col-span-2">
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusColors[item.status]}">
                            ${statusNames[item.status]}
                        </span>
                    </div>
                    <!-- 优先级列 -->
                    <div class="col-span-1">
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${priorityColors[item.priority]}">
                            ${priorityNames[item.priority]}
                        </span>
                    </div>
                    <!-- 负责人列 -->
                    <div class="col-span-2 text-sm text-gray-600">
                        ${item.assignee ? item.assignee.name : '未分配'}
                    </div>
                    <!-- 创建时间列 -->
                    <div class="col-span-2 text-sm text-gray-500">
                        ${new Date(item.created_at).toLocaleDateString()}
                    </div>
                    <!-- 操作列 -->
                    <div class="col-span-1">
                        <div class="flex space-x-1">
                            <button class="text-blue-600 hover:text-blue-800 text-sm" onclick="viewItem(${item.id})" title="查看">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                                </svg>
                            </button>
                            <button class="text-green-600 hover:text-green-800 text-sm" onclick="editItem(${item.id})" title="编辑">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>
            `);
        }
        
        function getTypeName(type) {
            const names = {
                'task': '任务',
                'issue': '问题',
                'requirement': '需求'
            };
            return names[type] || type;
        }
        
        // 查看Item详情
        function viewItem(itemId) {
            window.location.href = `/items/${itemId}`;
        }
        
        // 编辑Item
        function editItem(itemId) {
            window.location.href = `/items/${itemId}/edit`;
        }
        
        // Item卡片点击事件（排除操作按钮）
        $(document).on('click', '.item-card', function(e) {
            // 如果点击的是操作按钮，不执行跳转
            if ($(e.target).closest('button').length > 0) {
                return;
            }
            const itemId = $(this).data('item-id');
            window.location.href = `/items/${itemId}`;
        });
        
        function showNotification(message, type) {
            const bgColor = type === 'success' ? 'bg-green-500' : 'bg-red-500';
            const notification = $(`
                <div class="fixed top-4 right-4 ${bgColor} text-white px-6 py-3 rounded-lg shadow-lg z-50">
                    ${message}
                </div>
            `);
            
            $('body').append(notification);
            
            setTimeout(function() {
                notification.fadeOut(function() {
                    notification.remove();
                });
            }, 3000);
        }
    </script>
</body>
</html>
